package com.dreamo.pache;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Ticket preview pane added to the ticket_preview layout to display the camera preview content.
 * TODO(gjiang): Cropped viewfinder with alpha transparent overlay maybe added here.
 *
 * @author steve.jiang@gmail.com (Steve Jiang)
 */
public class TicketPreview extends SurfaceView implements SurfaceHolder.Callback {
    private Camera mCamera;

    public TicketPreview(Context context) {
        super(context);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        getHolder().addCallback(this);
    }

    /**
     * Set the camera resource.
     *
     * @param camera Camera resource active for the surface view.
     */
    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {
            requestLayout();
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            // TODO(gjiang): Create centralized tags for logs.
            Log.d("tag_camset", "Error setting camera preview: " + e.getMessage());
        }
    }

    /** NOTE(gjiang): Camera release will be in done in ScanActivity */
    public void surfaceDestroyed(SurfaceHolder holder) {}

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (holder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();

        } catch (Exception e){
            // TODO(gjiang): Create centralized tags for logs.
            Log.d("tag_camsta", "Error starting camera preview: " + e.getMessage());
        }
    }
}